package com.tl.ip_location_relation_v4.utils;

import redis.clients.jedis.Jedis;

/**
 * 
 * @author Antg
 * @date 2021年7月13日
 * @Description 获取redis工具类,单利模式
 */
public class RedisUtil {
	private static Jedis jedis;
	private static RedisUtil redisUtil;

	// 默认reids
	private RedisUtil() {
		this.jedis = new Jedis("127.0.0.1", 6379);
	}

	// 无密码使用
	private RedisUtil(String host, int port) {
		this.jedis = new Jedis(host, port);
	}

	// 带密码使用
	private RedisUtil(String host, int port, String password) {
		this.jedis = new Jedis(host, port);
		jedis.auth(password);
	}

	// 获取RedisUtil实例,本机ip与默认端口
	public static RedisUtil getInstance() {
		if (redisUtil == null) {
			synchronized (RedisUtil.class) {
				if (redisUtil == null) {
					redisUtil = new RedisUtil();
				}
			}

		}
		return redisUtil;
	}

	// 获取RedisUtil实例(没有密码保护)
	public static RedisUtil getInstance(String host, int port) {
		if (redisUtil == null) {
			synchronized (RedisUtil.class) {
				if (redisUtil == null) {
					redisUtil = new RedisUtil(host, port);
				}
			}

		}
		return redisUtil;
	}

	// 获取RedisUtil实例(有密码保护)
	public static RedisUtil getInstance(String host, int port, String password) {
		if (redisUtil == null) {
			synchronized (RedisUtil.class) {
				if (redisUtil == null) {
					redisUtil = new RedisUtil(host, port, password);
				}
			}

		}
		return redisUtil;
	}

	// 获取jedis实例
	public Jedis getJedis() {
		return this.jedis;
	}

	// 设置值
	public void set(String key, String value) {
		jedis.set(key, value);
	}

	// 读取值
	public String get(String key) {
		return jedis.get(key);
	}

	// 判断redis是否可用
	public boolean isOk(Jedis jedis) {
		boolean flag = false;
		try {
			if (jedis.ping().equalsIgnoreCase("PONG")) {
				flag = true;
			}
		} catch (Exception e) {
			flag = false;
			System.out.println("redis服务未开启或不可用");
		}
		return flag;
	}

}
